import React, { useState } from 'react';
import { Input, Button, Toast, Radio, Space } from 'antd-mobile';
import { UserOutline, LockOutline, MailOutline } from 'antd-mobile-icons';
import { history } from 'umi';
import styles from './index.less';
import { userAPI } from '@/services/api';

const Login: React.FC = () => {
    const [formType, setFormType] = useState<'login' | 'register'>('login');
    const [loginForm, setLoginForm] = useState({
        username: '',
        password: '',
    });
    const [registerForm, setRegisterForm] = useState({
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        email: '',
        role: 'student' as 'student' | 'teacher',
    });
    const [token, setToken] = useState('');

    const handleLogin = async () => {
        try {
            const res = await userAPI.login({
                username: loginForm.username,
                password: loginForm.password,
            });
            
            if (res.code === 200) {
                setToken(res.data.token);
                localStorage.setItem('token', res.data.token);
                
                Toast.show({
                    icon: 'success',
                    content: '登录成功',
                    duration: 1000,
                });
                
                setTimeout(() => {
                    history.replace('/home');
                }, 300);
            }
        } catch (error) {
            Toast.show({
                icon: 'fail',
                content: '登录失败',
            });
        }
    };

    const handleRegister = async () => {
        const { username, password, confirmPassword, phone, email, role } = registerForm;
        
        if (!username || !password || !confirmPassword || !phone || !email) {
            Toast.show({
                icon: 'fail',
                content: '请填写所有必填项',
            });
            return;
        }

        if (password !== confirmPassword) {
            Toast.show({
                icon: 'fail',
                content: '两次输入的密码不一致',
            });
            return;
        }

        try {
            await userAPI.register({
                username,
                password,
                phone,
                email,
                role,
            });
            
            Toast.show({
                icon: 'success',
                content: '注册成功，请登录',
            });
            setFormType('login');
        } catch (error) {
            // 错误已经被拦截器处理了
            console.error('Register failed:', error);
        }
    };

    return (
        <div className={styles.home}>
            <div className={styles.homtLogin}>
                <div className={styles.homtLoginTitle}>
                    {formType === 'login' ? '登录' : '注册'}
                </div>
                <div className={styles.loginForm}>
                    {formType === 'login' ? (
                        <>
                            <div className={styles.inputWrapper}>
                                <UserOutline className={styles.icon} />
                                <Input
                                    className={styles.input}
                                    placeholder="请输入用户名"
                                    value={loginForm.username}
                                    onChange={(val) => setLoginForm((prev) => ({ ...prev, username: val }))}
                                />
                            </div>
                            <div className={styles.inputWrapper}>
                                <LockOutline className={styles.icon} />
                                <Input
                                    className={styles.input}
                                    type="password"
                                    placeholder="请输入密码"
                                    value={loginForm.password}
                                    onChange={(val) => setLoginForm((prev) => ({ ...prev, password: val }))}
                                />
                            </div>
                            <Button
                                block
                                color="primary"
                                className={styles.loginButton}
                                onClick={handleLogin}
                            >
                                登录
                            </Button>
                            <div className={styles.switchForm}>
                                还没有账号？
                                <span onClick={() => setFormType('register')}>
                                    立即注册
                                </span>
                            </div>
                        </>
                    ) : (
                        <>
                            <div className={styles.inputWrapper}>
                                <UserOutline className={styles.icon} />
                                <Input
                                    className={styles.input}
                                    placeholder="请输入用户名"
                                    value={registerForm.username}
                                    onChange={(val) => setRegisterForm((prev) => ({ ...prev, username: val }))}
                                />
                            </div>
                            <div className={styles.inputWrapper}>
                                <LockOutline className={styles.icon} />
                                <Input
                                    className={styles.input}
                                    type="password"
                                    placeholder="请输入密码"
                                    value={registerForm.password}
                                    onChange={(val) => setRegisterForm((prev) => ({ ...prev, password: val }))}
                                />
                            </div>
                            <div className={styles.inputWrapper}>
                                <LockOutline className={styles.icon} />
                                <Input
                                    className={styles.input}
                                    type="password"
                                    placeholder="请确认密码"
                                    value={registerForm.confirmPassword}
                                    onChange={(val) => setRegisterForm((prev) => ({ ...prev, confirmPassword: val }))}
                                />
                            </div>
                            <div className={styles.inputWrapper}>
                                <Input
                                    className={styles.input}
                                    placeholder="请输入手机号"
                                    value={registerForm.phone}
                                    onChange={(val) => setRegisterForm((prev) => ({ ...prev, phone: val }))}
                                />
                            </div>
                            <div className={styles.inputWrapper}>
                                <MailOutline className={styles.icon} />
                                <Input
                                    className={styles.input}
                                    placeholder="请输入邮箱"
                                    value={registerForm.email}
                                    onChange={(val) => setRegisterForm((prev) => ({ ...prev, email: val }))}
                                />
                            </div>
                            <div className={styles.roleSelect}>
                                <Radio.Group
                                    value={registerForm.role}
                                    onChange={(val) => setRegisterForm((prev) => ({ ...prev, role: val as 'student' | 'teacher' }))}
                                >
                                    <Space direction="horizontal">
                                        <Radio value="student">学员</Radio>
                                        <Radio value="teacher">教师</Radio>
                                    </Space>
                                </Radio.Group>
                            </div>
                            <Button
                                block
                                color="primary"
                                className={styles.loginButton}
                                onClick={handleRegister}
                            >
                                注册
                            </Button>
                            <div className={styles.switchForm}>
                                已有账号？
                                <span onClick={() => setFormType('login')}>
                                    返回登录
                                </span>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
};

export default Login;